<template>
  <view class="uni-container">
    <uni-forms ref="formRef" v-model="formData" :rules="rules" validateTrigger="blur">
		<uni-forms-item name="classid" label="所属分类" required>
		  <uni-data-select
		    v-model="formData.classid"
		    :localdata="classifyOptions"
		    :clear="false"
		    placeholder="请选择分类"
		  />
		</uni-forms-item>
      <uni-forms-item name="picurl" label="壁纸图片" required>
        <iss-image-upload 
          v-model="formData.picurl" 
          upload-path="wallpaper/images"
		  :max-count="formData._id ? 1 : 10"
          ref="imageUploadRef"
          :max-width="1920"
          :max-height="1080"
        />
      </uni-forms-item>
      <uni-forms-item name="recommendLevel" label="推荐级别" required>
		  <iss-dict-select v-model="formData.recommendLevel" dictType='RecommendType' 
		  placeholder='请选择推荐级别'/>
	  </uni-forms-item>
      <uni-forms-item name="description" label="描述">
        <uni-easyinput v-model="formData.description" placeholder="请输入壁纸描述"/>
      </uni-forms-item>
      <uni-forms-item name="tabs" label="标签">
        <iss-tags-mod v-model="formData.tabs" :max="5" />
      </uni-forms-item>
      <uni-forms-item name="score" label="评分">
        <uni-rate 
          v-model="formData.score" 
          :max="5" 
          allow-half 
          :step="0.5"
        />
        <text class="score-text">{{formData.score}}分</text>
      </uni-forms-item>
<!--      <uni-forms-item name="nickname" label="上传者昵称">
        <uni-easyinput v-model="formData.nickname" placeholder="请输入上传者昵称" />
      </uni-forms-item> -->
      <uni-forms-item name="status" label="审核状态">
        <switch @change="binddata('status', $event.detail.value)" :checked="formData.status" />
      </uni-forms-item>
      <view class="uni-button-group">
        <button style="width: 100px;" type="primary" class="uni-button"
          @click="submitForm">{{$t('common.button.submit')}}</button>
        <button style="width: 100px; margin-left: 15px;"
          class="uni-button" @click="navigateBack(false)">{{$t('common.button.back')}}</button>
      </view>
    </uni-forms>
  </view>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  import { cloudIdToUrl } from '@/utils/common.js'
  import IssImageUpload from '@/components/iss-image-uplaod/iss-image-uplaod.vue'
  import { useForm } from '@/utils/composable'
  
  const wallpaperObj = uniCloud.importObject("iss-wallpaper")
  
  const formRef = ref(null)
  const imageUploadRef = ref(null)
  
  // 分类选项
  const classifyOptions = ref([])
  
  // 表单数据
  const formData = ref({
    picurl: '',
    classid: '',
	recommendLevel: '',
    description: '',
    tabs: [],
    score: 3,
    nickname: '',
    status: false
  })
  
  const rules = ref({
    picurl: {
      rules: [{
        required: true,
        errorMessage: '请上传{label}',
      }],
      label: '壁纸图片'
    },
    classid: {
      rules: [{
        required: true,
        errorMessage: '请选择{label}',
      }],
      label: '所属分类'
    },
    score: {
        rules: [{
          minimum: 0,
          maximum: 5,
          errorMessage: '评分必须是0-5之间的一位小数'
        }]
    }
  })
  
  // 加载分类选项
  const loadClassifyOptions = async () => {
    try {
      const res = await wallpaperObj.getClassifyOptions()
      if (res.code === 200) {
        classifyOptions.value = res.data.map(item => ({
          text: item.name,
          value: item._id
        }))
      }
    } catch (e) {
      console.error('加载分类选项失败:', e)
    }
  }
  
  const {submitForm,navigateBack} = useForm({
    title: '壁纸图片',
    formRef,
    formData,
    doc: wallpaperObj.doc_image,
    add: wallpaperObj.add_image,
    update: wallpaperObj.update_image,
    // 获取数据后的钩子
    onGetDataSucceed: (data)=>{
      // 将云存储ID转换为可访问的URL
      if(data.picurl) {
        let url = cloudIdToUrl(data.picurl)
        formData.value.picurl = url
      }
      // 确保tabs是数组
      if(!Array.isArray(data.tabs)) {
        formData.value.tabs = data.tabs ? [data.tabs] : []
      }
      // 转换评分为数字
      formData.value.score = parseFloat(data.score || '3.0')
    },
    // 在表单校验成功之后，在提交formData到数据库之前，需要做的异步操作
    beforeSubmitOptAsync: async () => {
      await imageUploadRef.value.uploadImage()
      // 确保score是字符串格式
      formData.value.score = formData.value.score.toString()
    }
  })
  
  onMounted(() => {
    loadClassifyOptions()
  })
</script>

<style lang="scss" scoped>
::v-deep .uni-forms-item__label {
  width: 90px !important;
}

.score-text {
  margin-left: 10px;
  color: #666;
  font-size: 14px;
}
</style>